package org.jxc.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.SessionFactory;
import org.jxc.dao.CustomerDAO;
import org.jxc.domain.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.team4.dao.DAOFactory;
import org.team4.domain.Users;
import org.team4.exception.CRUDException;
import org.team4.service.IService;
import org.team4.util.LoginBean;
import org.team4.util.Validate;
import org.team4.vo.Page;

@Service
public class CustomerService implements IService {

	private CustomerDAO customerDAO;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		customerDAO = (CustomerDAO) DAOFactory.getDAO(sessionFactory,
				CustomerDAO.class);
	}

	public Page<Customer> listPagionation(Page<Customer> page)
			throws CRUDException {
		Users user = LoginBean.getLoginBean().getUser();
		if (user.getDepartment().getManager().getId().equals(user.getId())) {
			return customerDAO.pagination(page,
					"from Customer where deleteFlag = '0'", null);
		} else {
			return customerDAO.pagination(page,
					"from Customer where deleteFlag = '0' and creator.id='"
							+ user.getId() + "' ", null);
		}
	}

	public List<Customer> findByOperator() throws CRUDException {
		return customerDAO.findByOperator();
	}

	public List<Customer> findCustomerByIds(String ids) throws CRUDException {
		List<Customer> sList = new ArrayList<Customer>();
		String[] s = ids.split(",");
		for (int i = 0; i < s.length; i++) {
			if (Validate.notNull(s[i])) {
				Customer su = customerDAO.get(s[i]);
				sList.add(su);
			}
		}
		return sList;
	}

	public void saveCustomer(Customer customer) throws CRUDException {
		customer.setDeleteFlag("0");
		customer.setCreator(LoginBean.getLoginBean().getUser());
		customer.setCreateTime(new Date());
		customerDAO.save(customer);
	}

	public Customer findCustomerById(String id) throws CRUDException {
		return customerDAO.get(id);
	}

	public void update(Customer customer) throws CRUDException {
		customerDAO.update(customer);
	}

	public void delete(String id) throws CRUDException {
		Customer customer = customerDAO.get(id);
		customer.setDeleteFlag("1");
		customerDAO.update(customer);
	}
}